package cn.yitun.chat.yitunserverrunsingleboot.chat.web;

import cn.yitun.chat.yitunchatbasesdk.server.im.dispatcher.handler.SessionMessageHandler;
import cn.yitun.chat.yituncommonlibutil.lib.YitunJsonUtil;
import cn.yitun.chat.yituncommonmessage.result.ResultMessage;
import cn.yitun.chat.yituncommonweb.util.YitunHttpUtil;
import cn.yitun.chat.yitungeneral.annotation.parameter.ParamDefine;
import cn.yitun.chat.yitunnetsession.session.AbstractSession;
import cn.yitun.chat.yitunnetsession.session.SocketSession;
import cn.yitun.chat.yitunserverimcore.bridge.main.common.auth.box.AuthBox;
import cn.yitun.chat.yitunservermanagecore.util.ResponseUtil;
import cn.yitun.chat.yitunservernetcore.server.general.main.common.session.SocketSessionBox;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author: yitun
 * @date: 2016年9月28日 上午11:24:56
 */
@Controller
@RequestMapping("/manage")
public class Portal {

	@Resource
	private AuthBox authBox;
	@Resource
	private SessionMessageHandler messageHandler;

	@ResponseBody
	@PostMapping(value = "/api")
	public Object api(@ParamDefine String body, HttpServletRequest request, HttpServletResponse response) {
		String data = request.getParameter("data");
		String message = body == null || "".equals(body) ? data : body;

		String token = request.getHeader("token");
		Long userId = authBox.getUserId(token);

		boolean auth = null != userId && userId != 0;

		SocketSession socketSession = new AbstractSession() {

			@Override
			public String getId() {
				HttpSession session = request.getSession();
				return session == null ? "" : session.getId();
			}

			@Override
			public void write(Object object) {
				ResponseUtil.putAllowOrigin(response);
				ResponseUtil.writer(response, YitunJsonUtil.objectToJson(object));
			}

			@Override
			public void close() {
				// TODO Auto-generated method stub
			}

			@Override
			public String getRemoteAddress() {
				return YitunHttpUtil.getIpAddr(request);
			}

		};

		socketSession.setAuth(auth);
		socketSession.setKey(userId);

		Object o = messageHandler.doMessage(message, socketSession);
		return o;
	}

	@Resource
	private SocketSessionBox socketSessionBox;

	@ResponseBody
	@PostMapping(value = "/main/sessionCount")
	public Object sessionCount() {
		ResultMessage message = new ResultMessage();
		message.bodyPut("count", socketSessionBox.getAllSet().size());
		return message;
	}
}
